//////////////////////////////////////////////////////////////////////////
/// Copyright (C), 1998-2016, rytec Corporation. All rights reserved.
/// \file       TimeEdit.cpp
/// \brief      
/// \author     wyf
/// \version    0.95
/// \date       2020-8
//////////////////////////////////////////////////////////////////////////

#include "TimeEdit.h"
#include "CalendarWidget.h"

#include <QHBoxLayout>
#include <QPushButton>

CRyTimeEdit::CRyTimeEdit(QWidget* parent) 
    : QTimeEdit(parent)
    , mPopupButton(NULL)
    , mCalendarWidget(NULL)
{
    mPopupButton = new QPushButton();
    mPopupButton->setFixedSize(QSize(15, 15));
    mPopupButton->setCursor(QCursor(Qt::PointingHandCursor));
    mPopupButton->setStyleSheet(
        "QPushButton:hover{ background-color:rgba(37, 155, 243, 0.41); }"
        "QPushButton:pressed{ background-color:rgba(37, 155, 243, 0.99); }"
        "QPushButton{ border-image:url(:/Resources/PopupButton.png); }");

    QHBoxLayout *layout = new QHBoxLayout();
    layout->addStretch();
    layout->addWidget(mPopupButton);
    layout->setContentsMargins(0,0,20,0);
    setLayout(layout);

    mCalendarWidget = new CRyCalendarWidget(displayedSections(), this);
    mCalendarWidget->setDateTime(dateTime());

    connect(mPopupButton, &QAbstractButton::clicked, this, &CRyTimeEdit::onPopupButtonClicked);
    connect(mCalendarWidget, &CRyCalendarWidget::dataTimeChanged, this, &CRyTimeEdit::onDateTimeChanged);
}

CRyTimeEdit::~CRyTimeEdit()
{
    delete mCalendarWidget;
    mCalendarWidget = NULL;
}

void CRyTimeEdit::onPopupButtonClicked()
{
    QPoint position(0, height());
    position = mapToGlobal(position);

    mCalendarWidget->setDateTime(dateTime());
    mCalendarWidget->move(position);
    mCalendarWidget->show();
}

void CRyTimeEdit::onDateTimeChanged(const QDateTime& dateTime)
{
    setDateTime(dateTime);
}

void CRyTimeEdit::setDisplayFormat(const QString &format)
{
    QDateTimeEdit::setDisplayFormat(format);
    mCalendarWidget->setDisplaySections(displayedSections());
}
